package com.banshuibao.bsb_android.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.MyApplication;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.download.DownloadService;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.model.DownloadInfo;
import com.banshuibao.bsb_android.model.EventStatusModel;
import com.banshuibao.bsb_android.util.CCMediaConfig;
import com.banshuibao.bsb_android.util.DataSet;
import com.banshuibao.bsb_android.util.GetLoginInfo;
import com.banshuibao.bsb_android.util.LogUtil;
import com.banshuibao.bsb_android.util.MediaUtil;
import com.banshuibao.bsb_android.util.ParamsUtil;
import com.banshuibao.bsb_android.util.ShareUtil;
import com.banshuibao.bsb_android.util.XToast;
import com.banshuibao.bsb_android.view.VerticalSeekBar;
import com.bokecc.sdk.mobile.download.Downloader;
import com.bokecc.sdk.mobile.play.DWMediaPlayer;
import com.bokecc.sdk.mobile.util.HttpUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import java.io.File;
import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zyh on 2017/9/22.
 */

public class EventMediaPlayerActivity extends Activity implements DWMediaPlayer.OnBufferingUpdateListener, DWMediaPlayer.OnInfoListener,
        DWMediaPlayer.OnPreparedListener, DWMediaPlayer.OnErrorListener,
        MediaPlayer.OnVideoSizeChangedListener, SurfaceHolder.Callback,
        MediaPlayer.OnCompletionListener {

    private String title;
    private String videoId;
    private String id;
    private String USER_ID;
    private String APK_ID;
    private String shareUrl;
    private String imgUrl;

    private boolean networkConnected = true;
    private DWMediaPlayer player;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private ProgressBar bufferProgressBar;
    private SeekBar skbProgress;
    private TextView playDuration, videoDuration;
    private LinearLayout playerBottomLayout, playerTopLayout;
    private AudioManager audioManager;
    private VerticalSeekBar volumeSeekBar;
    private int currentVolume;
    private int maxVolume;

    private boolean isPrepared;
    private Map<String, Integer> definitionMap;

    private Handler playerHandler;
    private Timer timer = new Timer();
    private TimerTask timerTask, networkInfoTimerTask;

    private int currentScreenSizeFlag = 1;
    private int currentDefinitionIndex = 0;
    // 默认设置为普清
    private int defaultDefinition = DWMediaPlayer.NORMAL_DEFINITION;

    private boolean isPlaying;
    // 当player未准备好，并且当前activity经过onPause()生命周期时，此值为true
    private boolean isFreeze = false;
    private boolean isSurfaceDestroy = false;

    private int currentPosition;

    private String[] definitionArray;
    private final String[] screenSizeArray = new String[]{"满屏", "100%", "75%", "50%"};

    private GestureDetector detector;
    private float scrollTotalDistance;
    private int lastPlayPosition, currentPlayPosition;
    private RelativeLayout rlPlay;
    private WindowManager wm;
    private ImageView media_play_bg;

    private boolean listComplete, detailComplete;
    // 隐藏界面的线程
    private Runnable hidePlayRunnable = new Runnable() {
        @Override
        public void run() {
            setLayoutVisibility(View.GONE, false);
        }
    };

    private boolean isComplete = true;
    private boolean isPause;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setContentView(R.layout.activity_media_detail);
        wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        detector = new GestureDetector(this, new MyGesture());
        initData();
        initView();
        initNetworkTimerTask();
        initPlayHandler();
        initPlayInfo();
        HttpUtil.LOG_LEVEL = HttpUtil.HttpLogLevel.CLOSE;
    }

    private void initData() {
        //setActivity_title("点播间");
        USER_ID = CCMediaConfig.USER_ID;
        APK_ID = CCMediaConfig.APP_KEY;
        videoId = getIntent().getStringExtra("videoId");
        id = getIntent().getStringExtra("id");
        shareUrl = getIntent().getStringExtra("share_url");
        imgUrl = getIntent().getStringExtra("img");
    }


    private void initNetworkTimerTask() {
        networkInfoTimerTask = new TimerTask() {
            @Override
            public void run() {
                if (isPause)
                    return;
                parseNetworkInfo();
            }
        };
        timer.schedule(networkInfoTimerTask, 0, 600);
    }

    enum NetworkStatus {
        WIFI,
        MOBILEWEB,
        NETLESS,
    }

    private NetworkStatus currentNetworkStatus;
    ConnectivityManager cm;

    private void parseNetworkInfo() {
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                if (currentNetworkStatus != null && currentNetworkStatus == NetworkStatus.WIFI) {
                    return;
                } else {
                    currentNetworkStatus = NetworkStatus.WIFI;
                }

            } else {
                if (currentNetworkStatus != null && currentNetworkStatus == NetworkStatus.MOBILEWEB) {
                    return;
                } else {
                    currentNetworkStatus = NetworkStatus.MOBILEWEB;
                    showMobileDialog();
                }
            }

            startPlayerTimerTask();
            networkConnected = true;
        } else {
            if (currentNetworkStatus != null && currentNetworkStatus == NetworkStatus.NETLESS) {
                return;
            } else {
                currentNetworkStatus = NetworkStatus.NETLESS;
                showNetlessToast();
            }

            if (timerTask != null) {
                timerTask.cancel();
            }

            networkConnected = false;
        }
    }

    private void showMobileDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(EventMediaPlayerActivity.this);
                AlertDialog dialog = builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).setPositiveButton("继续", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setMessage("当前为移动网络，是否继续播放？").create();

                dialog.show();
            }
        });

    }

    private void showNetlessToast() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                XToast.showToast(EventMediaPlayerActivity.this, "当前无网络信号，无法播放");
            }
        });
    }

    private void startPlayerTimerTask() {
        if (timerTask != null) {
            timerTask.cancel();
        }
        timerTask = new TimerTask() {
            @Override
            public void run() {

                if (!isPrepared) {
                    return;
                }

                playerHandler.sendEmptyMessage(0);
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    private ImageView ivCenterPlay, back_iv;
    private ImageView iv_sound;
    private ImageView ivBackVideo, ivNextVideo, ivPlay;

    private void initView() {

        rlPlay = findViewById(R.id.rl_play);

        rlPlay.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!isPrepared) {
                    return true;
                }
                resetHideDelayed();
                // 事件监听交给手势类来处理
                detector.onTouchEvent(event);
                return true;
            }
        });

        rlPlay.setClickable(true);
        rlPlay.setLongClickable(true);
        rlPlay.setFocusable(true);

        surfaceView = findViewById(R.id.playerSurfaceView);
        //防止surfaceView滑动延迟
        surfaceView.postDelayed(new Runnable() {
            @Override
            public void run() {
                surfaceView.setVisibility(View.VISIBLE);
            }
        }, 200);
        bufferProgressBar = findViewById(R.id.bufferProgressBar);

        ivCenterPlay = findViewById(R.id.iv_center_play);
        ivCenterPlay.setOnClickListener(onClickListener);

        playDuration = findViewById(R.id.playDuration);
        videoDuration = findViewById(R.id.videoDuration);
        playDuration.setText(ParamsUtil.millsecondsToStr(0));
        videoDuration.setText(ParamsUtil.millsecondsToStr(0));

        ivBackVideo = findViewById(R.id.iv_video_back);
        ivNextVideo = findViewById(R.id.iv_video_next);
        ivBackVideo.setVisibility(View.GONE);
        ivNextVideo.setVisibility(View.GONE);
        ivPlay = findViewById(R.id.iv_play);

        //ivBackVideo.setOnClickListener(onClickListener);
        //ivNextVideo.setOnClickListener(onClickListener);
        ivPlay.setOnClickListener(onClickListener);

        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        volumeSeekBar = findViewById(R.id.volumeSeekBar);
        iv_sound = findViewById(R.id.iv_sound);
        iv_sound.setOnClickListener(onClickListener);
        volumeSeekBar.setThumbOffset(2);

        volumeSeekBar.setMax(maxVolume);
        volumeSeekBar.setProgress(currentVolume);
        volumeSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        skbProgress = findViewById(R.id.skbProgress);
        skbProgress.setOnSeekBarChangeListener(onSeekBarChangeListener);

        playerBottomLayout = findViewById(R.id.playerBottomLayout);
        playerTopLayout = findViewById(R.id.playerTopLayout);

        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); //2.3及以下使用，不然出现只有声音没有图像的问题
        surfaceHolder.addCallback(this);

        media_play_bg = findViewById(R.id.media_play_bg);
        back_iv = findViewById(R.id.back_iv);
        back_iv.setOnClickListener(onClickListener);

        ImageView share = findViewById(R.id.share);
        share.setOnClickListener(onClickListener);
        ImageView iv_share = findViewById(R.id.iv_share);
        iv_share.setOnClickListener(onClickListener);
        ImageView download = findViewById(R.id.download);
        if (DataSet.hasDownloadInfo(videoId)) {
            download.setVisibility(View.GONE);
        } else {
            download.setVisibility(View.VISIBLE);
            download.setOnClickListener(onClickListener);
        }
    }

    private void showShare() {
        if (player != null) {
            if (player.isPlaying()) {
                player.pause();
                ivCenterPlay.setVisibility(View.VISIBLE);
                ivPlay.setImageResource(R.drawable.smallbegin_ic);
            }
            GetLoginInfo getLoginInfo = MyApplication.applicationInstance.getLoginInfo();
            ShareUtil.showShare(EventMediaPlayerActivity.this,
                    shareUrl + "?firmId=" + getLoginInfo.getFirmId() + "&inviteUserId=" + getLoginInfo.getUserId() + "&imgUrl=" + imgUrl,
                    player.getVideoTitle(), "", null);
        }
    }

    private long saveTime = 0;

    private void initPlayHandler() {
        playerHandler = new Handler() {
            public void handleMessage(Message msg) {

                if (player == null) {
                    return;
                }
                if (player.isPlaying()) {
                    saveTime += 1000;
                }

                // 更新播放进度
                currentPlayPosition = player.getCurrentPosition();
                int duration = player.getDuration();

                if (duration > 0) {
                    long pos = skbProgress.getMax() * currentPlayPosition / duration;
                    playDuration.setText(ParamsUtil.millsecondsToStr(player.getCurrentPosition()));
                    skbProgress.setProgress((int) pos);
                }
            }
        };
    }

    private void initPlayInfo() {

        isPrepared = false;
        player = new DWMediaPlayer();
        player.reset();
        player.setOnErrorListener(this);
        player.setOnCompletionListener(this);
        player.setOnVideoSizeChangedListener(this);
        player.setOnInfoListener(this);
        if (!TextUtils.isEmpty(videoId))
            try {
                // 播放线上视频
                player.setVideoPlayInfo(videoId, USER_ID, APK_ID, this);
                // 设置默认清晰度
                player.setDefaultDefinition(defaultDefinition);
                //关闭默认图片
                if (media_play_bg.getVisibility() != View.GONE)
                    media_play_bg.setVisibility(View.GONE);
                //设置播放title
                ivCenterPlay.setVisibility(View.GONE);
                bufferProgressBar.setVisibility(View.VISIBLE);
                isPlaying = true;
            } catch (IllegalArgumentException e) {
                LogUtil.e("player error", e.getMessage());
            } catch (SecurityException e) {
                LogUtil.e("player error", e.getMessage());
            } catch (IllegalStateException e) {
                LogUtil.e("player error", e + "");
            }
    }

    private RelativeLayout.LayoutParams getScreenSizeParams(int position) {
        currentScreenSizeFlag = position;
        int width = 600;
        int height = 400;

        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();

        String screenSizeStr = screenSizeArray[position];
        if (screenSizeStr.indexOf("%") > 0) {// 按比例缩放
            int vWidth = player.getVideoWidth();
            if (vWidth == 0) {
                vWidth = 600;
            }

            int vHeight = player.getVideoHeight();
            if (vHeight == 0) {
                vHeight = 400;
            }

            if (vWidth > width || vHeight > height) {
                float wRatio = (float) vWidth / (float) width;
                float hRatio = (float) vHeight / (float) height;
                float ratio = Math.max(wRatio, hRatio);

                width = (int) Math.ceil((float) vWidth / ratio);
                height = (int) Math.ceil((float) vHeight / ratio);
            } else {
                float wRatio = (float) width / (float) vWidth;
                float hRatio = (float) height / (float) vHeight;
                float ratio = Math.min(wRatio, hRatio);

                width = (int) Math.ceil((float) vWidth * ratio);
                height = (int) Math.ceil((float) vHeight * ratio);
            }


            int screenSize = ParamsUtil.getInt(screenSizeStr.substring(0, screenSizeStr.indexOf("%")));
            width = (width * screenSize) / 100;
            height = (height * screenSize) / 100;
        }

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
        return params;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            player.setOnBufferingUpdateListener(this);
            player.setOnPreparedListener(this);
            player.setDisplay(holder);
            player.setScreenOnWhilePlaying(true);

            player.prepareAsync();
        } catch (Exception e) {
            LogUtil.e("videoPlayer", e.fillInStackTrace());
        }
        LogUtil.e("videoPlayer", "surface created");
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        holder.setFixedSize(width, height);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (player == null) {
            return;
        }
        if (isPrepared) {
            currentPosition = player.getCurrentPosition();
        }

        isPrepared = false;
        isSurfaceDestroy = true;

        player.stop();
        player.reset();

    }

    private void initTimerTask() {
        if (timerTask != null) {
            timerTask.cancel();
        }

        timerTask = new TimerTask() {
            @Override
            public void run() {

                if (!isPrepared) {
                    return;
                }

                playerHandler.sendEmptyMessage(0);
            }
        };
        timer.schedule(timerTask, 0, 1000);

    }

    @Override
    public void onPrepared(MediaPlayer mp) {

        initTimerTask();
        isPrepared = true;
        if (!isFreeze) {
            if (isPlaying) {
                isComplete = false;
                player.start();
                ivPlay.setImageResource(R.drawable.smallstop_ic);
            } else if (!TextUtils.isEmpty(videoId)) {
                ivCenterPlay.setVisibility(View.VISIBLE);
                ivPlay.setImageResource(R.drawable.smallbegin_ic);
            }
        }
        if (currentPosition > 0) {
            player.seekTo(currentPosition);
        }
        definitionMap = player.getDefinitions();
        bufferProgressBar.setVisibility(View.GONE);
        setSurfaceViewLayout();
        videoDuration.setText(ParamsUtil.millsecondsToStr(player.getDuration()));
    }

    // 设置surfaceview的布局
    private void setSurfaceViewLayout() {
        RelativeLayout.LayoutParams params = getScreenSizeParams(currentScreenSizeFlag);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        surfaceView.setLayoutParams(params);
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        skbProgress.setSecondaryProgress(percent);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            resetHideDelayed();
            switch (v.getId()) {
                case R.id.iv_center_play:
                case R.id.iv_play:
                    if (TextUtils.isEmpty(videoId)) {
                        XToast.showToast(EventMediaPlayerActivity.this, "暂无相关视频");
                        return;
                    }
                    if (!isComplete)
                        changePlayStatus();
                    else
                        startToPlay();
                    break;
                case R.id.iv_sound:
                    if (volumeSeekBar.isShown())
                        volumeSeekBar.setVisibility(View.GONE);
                    else
                        volumeSeekBar.setVisibility(View.VISIBLE);
                    break;
                case R.id.back_iv:
                    finish();
                    break;
                case R.id.iv_share:
                case R.id.share:
                    showShare();
                    break;
                case R.id.download:
                    downloadCurrentVideo();
                    break;

            }
        }
    };

    private boolean isLoading;

    private void downloadCurrentVideo() {
        if (isLoading)
            return;
        if (player == null)
            return;
        if (DataSet.hasDownloadInfo(videoId)) {
            if (DataSet.getDownloadInfo(videoId).getStatus() != Downloader.FINISH) {
                XToast.showToast(this, "文件下载中,请到我的下载中查看");
            }
            XToast.showToast(this, "文件已存在");
            return;
        }
        String userId = MyApplication.applicationInstance.getLoginInfo().getUserId();
        File file = MediaUtil.createFile(CCMediaConfig.DOWNLOAD_DIR + userId, videoId);
        if (file == null) {
            //XToast.showToast(this, "创建文件失败");
            return;
        }
        Glide.with(this).load(Constants.Url.SHOW_IMAGE + imgUrl).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
            @Override
            public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
                try {
                    String img = Base64.encodeToString(bytes, Base64.DEFAULT);
                    downloadStart(img);
                } catch (Exception e) {
                    isLoading = false;
                    downloadStart("");
                }
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                super.onLoadFailed(e, errorDrawable);
                downloadStart("");
            }
        });
        isLoading = true;
        XToast.showToast(EventMediaPlayerActivity.this, "正在加载下载数据");
    }

    private void downloadStart(String img) {
        DataSet.addDownloadInfo(new DownloadInfo(videoId, videoId,
                0, null, Downloader.WAIT, new Date(),
                player.getVideoTitle(), img, id, imgUrl, shareUrl));
        Intent service = new Intent(this, DownloadService.class);
        service.putExtra("title", videoId);
        startService(service);
        XToast.showToast(this, "文件已加入下载队列");
        isLoading = false;
    }


    private void changeVideo() {

        isPrepared = false;
        isPlaying = true;

        setLayoutVisibility(View.GONE, false);
        bufferProgressBar.setVisibility(View.VISIBLE);
        ivCenterPlay.setVisibility(View.GONE);

        currentPosition = 0;
        currentPlayPosition = 0;
        timerTask.cancel();

        player.pause();
        player.stop();
        player.reset();
        player.setDefaultDefinition(defaultDefinition);
        player.setVideoPlayInfo(videoId, USER_ID, APK_ID, this);
        //关闭默认图片
        if (media_play_bg.getVisibility() != View.GONE)
            media_play_bg.setVisibility(View.GONE);
        player.setDisplay(surfaceHolder);
        player.prepareAsync();
    }

    private void toastInfo(String info) {
        XToast.showToast(this, info);
    }

    SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        int progress = 0;

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (networkConnected) {
                player.seekTo(progress);
                playerHandler.postDelayed(hidePlayRunnable, 5000);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            playerHandler.removeCallbacks(hidePlayRunnable);
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (networkConnected) {
                this.progress = progress * player.getDuration() / seekBar.getMax();
            }
        }
    };

    VerticalSeekBar.OnSeekBarChangeListener seekBarChangeListener = new VerticalSeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
            currentVolume = progress;
            volumeSeekBar.setProgress(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            playerHandler.removeCallbacks(hidePlayRunnable);
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            playerHandler.postDelayed(hidePlayRunnable, 5000);
        }

    };

    // 控制播放器面板显示
    private boolean isDisplay = false;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // 监测音量变化
        if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN
                || event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {

            int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (currentVolume != volume) {
                currentVolume = volume;
                volumeSeekBar.setProgress(currentVolume);
            }

            if (isPrepared) {
                setLayoutVisibility(View.VISIBLE, true);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * @param visibility 显示状态
     * @param isDisplay  是否延迟消失
     */
    private void setLayoutVisibility(int visibility, boolean isDisplay) {
        if (player == null || player.getDuration() <= 0) {
            return;
        }

        playerHandler.removeCallbacks(hidePlayRunnable);

        this.isDisplay = isDisplay;


        if (isDisplay) {
            playerHandler.postDelayed(hidePlayRunnable, 5000);
        }

        playerBottomLayout.setVisibility(visibility);
        playerTopLayout.setVisibility(visibility);
        volumeSeekBar.setVisibility(View.GONE);
    }

    private Handler alertHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            toastInfo("视频异常，无法播放。");
            super.handleMessage(msg);
        }

    };

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        if (what == -38)
            return false;
        Message msg = new Message();
        msg.what = what;
        if (alertHandler != null) {
            alertHandler.sendMessage(msg);
        }
        return false;
    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        setSurfaceViewLayout();
    }


    // 重置隐藏界面组件的延迟时间
    private void resetHideDelayed() {
        playerHandler.removeCallbacks(hidePlayRunnable);
        playerHandler.postDelayed(hidePlayRunnable, 5000);
    }

    // 手势监听器类
    private class MyGesture extends GestureDetector.SimpleOnGestureListener {

        private Boolean isVideo;
        private float scrollCurrentPosition;
        private float scrollCurrentVolume;

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return super.onSingleTapUp(e);
        }

        @Override
        public void onLongPress(MotionEvent e) {
            super.onLongPress(e);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

            if (isVideo == null) {
                if (Math.abs(distanceX) > Math.abs(distanceY)) {
                    isVideo = true;
                } else {
                    isVideo = false;
                }
            }

            if (isVideo.booleanValue()) {
                parseVideoScroll(distanceX);
            } else {
                parseAudioScroll(distanceY);
            }

            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        private void parseVideoScroll(float distanceX) {
            if (!isDisplay) {
                setLayoutVisibility(View.VISIBLE, true);
            }

            scrollTotalDistance += distanceX;

            float duration = (float) player.getDuration();

            float width = wm.getDefaultDisplay().getWidth() * 0.75f; // 设定总长度是多少，此处根据实际调整
            //右滑distanceX为负
            float currentPosition = scrollCurrentPosition - (float) duration * scrollTotalDistance / width;

            if (currentPosition < 0) {
                currentPosition = 0;
            } else if (currentPosition > duration) {
                currentPosition = duration;
            }

            player.seekTo((int) currentPosition);

            playDuration.setText(ParamsUtil.millsecondsToStr((int) currentPosition));
            int pos = (int) (skbProgress.getMax() * currentPosition / duration);
            skbProgress.setProgress(pos);
        }

        private void parseAudioScroll(float distanceY) {
            if (!isDisplay) {
                setLayoutVisibility(View.VISIBLE, true);
            }
            volumeSeekBar.setVisibility(View.VISIBLE);
            scrollTotalDistance += distanceY;

            float height = wm.getDefaultDisplay().getHeight() * 0.75f;
            // 上滑distanceY为正
            currentVolume = (int) (scrollCurrentVolume + maxVolume * scrollTotalDistance / height);

            if (currentVolume < 0) {
                currentVolume = 0;
            } else if (currentVolume > maxVolume) {
                currentVolume = maxVolume;
            }

            volumeSeekBar.setProgress(currentVolume);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return super.onFling(e1, e2, velocityX, velocityY);
        }

        @Override
        public void onShowPress(MotionEvent e) {
            super.onShowPress(e);
        }

        @Override
        public boolean onDown(MotionEvent e) {
            scrollTotalDistance = 0f;
            isVideo = null;

            scrollCurrentPosition = (float) player.getCurrentPosition();
            scrollCurrentVolume = currentVolume;

            return super.onDown(e);
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {

            if (!isDisplay) {
                setLayoutVisibility(View.VISIBLE, true);
            }
            changePlayStatus();
            return super.onDoubleTap(e);
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            return super.onDoubleTapEvent(e);
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (isDisplay) {
                setLayoutVisibility(View.GONE, false);
            } else {
                setLayoutVisibility(View.VISIBLE, true);
            }
            return super.onSingleTapConfirmed(e);
        }
    }

    private void changePlayStatus() {
        if (player.isPlaying()) {
            player.pause();
            ivCenterPlay.setVisibility(View.VISIBLE);
            ivPlay.setImageResource(R.drawable.smallbegin_ic);
        } else {
            player.start();
            ivCenterPlay.setVisibility(View.GONE);
            ivPlay.setImageResource(R.drawable.smallstop_ic);
        }
    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case DWMediaPlayer.MEDIA_INFO_BUFFERING_START:
                if (player.isPlaying()) {
                    bufferProgressBar.setVisibility(View.VISIBLE);
                }
                break;
            case DWMediaPlayer.MEDIA_INFO_BUFFERING_END:
                bufferProgressBar.setVisibility(View.GONE);
                break;
        }
        return false;
    }

    @Override
    public void onResume() {
        if (isFreeze) {
            isFreeze = false;
        }
        if (isPause && !isComplete && !TextUtils.isEmpty(videoId)) {
            if (!isPrepared) {
                bufferProgressBar.setVisibility(View.VISIBLE);
            } else {
                ivCenterPlay.setVisibility(View.VISIBLE);
                ivPlay.setImageResource(R.drawable.smallbegin_ic);
            }
            isPause = false;
        }
        super.onResume();
    }

    @Override
    public void onPause() {
        isPause = true;
        if (isPrepared) {
            isPlaying = false;
            player.pause();
        } else {
            // 如果播放器没有prepare完成，则设置isFreeze为true
            isFreeze = true;
        }
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (playerHandler != null) {
            playerHandler.removeCallbacksAndMessages(null);
            playerHandler = null;
        }
        if (alertHandler != null) {
            alertHandler.removeCallbacksAndMessages(null);
            alertHandler = null;
        }
        if (player != null) {
            player.reset();
            player.release();
            player = null;
        }
        if (networkInfoTimerTask != null) {
            networkInfoTimerTask.cancel();
            networkInfoTimerTask = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        super.onDestroy();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (isPrepared) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    currentPlayPosition = 0;
                    currentPosition = 0;
                    isComplete = true;
                    ivPlay.setImageResource(R.drawable.smallbegin_ic);
                    ivCenterPlay.setVisibility(View.VISIBLE);
                    playerBottomLayout.setVisibility(View.GONE);
                    toastInfo("播放完成");
                }
            });
        }
    }

    private void startToPlay() {
        if (TextUtils.isEmpty(videoId)) {
            XToast.showToast(this, "暂无相关视频");
            return;
        }
        isComplete = false;
        if (player == null) {
            initPlayInfo();
        } else
            changeVideo();
    }

    /**
     * 提交时长
     */
    private void submitTime() {
        EventStatusModel.Body body = new EventStatusModel.Body();
        body.setId(id);
        body.setPlayTime(saveTime);
        com.banshuibao.bsb_android.http.HttpUtil.doPost(Constants.Url.TIME_COMPE, body, new HttpResponse(this) {
            @Override
            public void onResult(Object obj) {

            }
        });
    }

    @Override
    public void finish() {
        submitTime();
        super.finish();
    }
}
